#include "inputtextedit.h"
#include "inputcontext.h"
#include "configmanager.h"

#include <QRegExp>
#include <QApplication>

InputTextEdit *InputTextEdit::m_instance = nullptr; 

InputTextEdit::InputTextEdit(QWidget *parent)
	: QTextEdit(parent)
    , m_pinyinHandler(new PinyinHandler(this))
    , m_candidateWindow(new CandidateWindow(this))
    , m_inputContext(InputContext::getInstance())
    , m_userDict(UserDict::getInstance())
{
	// init style
	QFont font("微软雅黑", 14);
    setFont(font);
    setStyleSheet(R"(
        QTextEdit { border: 1px solid #E0E0E0; border-radius: 4px; padding: 8px; }
        QTextEdit:focus { border: 1px solid #3498DB; outline: none; }
        QTextEdit:dark { background-color: #2C3E50; color: white; }
    )");
    setAcceptRichText(false); // 禁用富文本

	// init auto timer
	m_autoAddWordTimer.setInterval(15000);		// 延迟1.5s
	m_autoAddWordTimer.setSingleShot(true);
    connect(&m_autoAddWordTimer, &QTimer::timeout, this, &InputTextEdit::onAutoAddWordCheck);

	// 选中candidate insert text
	connect(m_candidateWindow, &CandidateWindow::candidateSelected, this, &InputTextEdit::onCandidateSelected);
    
	// hide english candidate
	connect(m_inputContext, &InputContext::cnEnModeChanged, this, [this](bool isCn) {
        if (!isCn) {
            hideCandidateWindow(); // 英文模式隐藏候选词
        }
    });
	qInfo() << "[InputTextEdit] 初始化完成";
}

InputTextEdit *InputTextEdit::getInstance(QWidget *parent)
{
	if (!m_instance) {
        static QMutex mutex;
        QMutexLocker locker(&mutex);
        if (!m_instance) {
            m_instance = new InputTextEdit(parent);
        }
    }
    return m_instance;
}

InputTextEdit::~InputTextEdit()
{
	m_instance = nullptr;
    qInfo() << "[InputTextEdit] 析构完成"
}

void InputTextEdit::hideCandidateWindow()
{
	if (m_candidateWindow->isVisible())	m_candidateWindow->hide();
}

/////////////////////////////////////////////////
// override 
void InputTextEdit::keyPressEvent(QKeyEvent *event)
{
	// 中文模式下处理拼音输入
    if (m_inputContext->isInComposition() && m_inputContext->composingText().isEmpty()) {
        QString key = event->text().toLower();
        if (QRegExp("[a-z]").exactMatch(key)) {
            // 传递按键给InputContext解析
            m_inputContext->processKeyPress(key);
            // 获取解析后的候选词，显示候选窗口
            QVector<PinyinCandidate> candidates = m_inputContext->currentCandidates();
            if (!candidates.isEmpty()) {
                m_candidateWindow->setCandidates(candidates);
                m_candidateWindow->moveBelowWidget(this); // 窗口定位在输入框下方
            }
            return;
        }
    }
	// backspace | enter
	if (event->key() == Qt::Key_Backspace) {
        m_inputContext->processKeyPress("Backspace");
        hideCandidateWindow();
    } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        m_inputContext->processKeyPress("Enter");
        hideCandidateWindow();
    }

    QTextEdit::keyPressEvent(event);
}

void InputTextEdit::focusInEvent(QFocusEvent *event)
{
	// 恢复未完成的候选词
	QTextEdit::focusInEvent(event);
    if (m_inputContext->isInComposition() && !m_inputContext->composingText().isEmpty()) {
        QVector<PinyinCandidate> candidates = m_inputContext->currentCandidates();
        if (!candidates.isEmpty()) {
            m_candidateWindow->setCandidates(candidates);
            m_candidateWindow->moveBelowWidget(this);
        }
    }
}

void InputTextEdit::focusOutEvent(QFocusEvent *event)
{
	// hide candidate
	QTextEdit::focusOutEvent(event);
    hideCandidateWindow();
}

// 繁简转换 实时
void InputTextEdit::textChanged()
{
	QTextEdit::textChanged();
    if (m_inputContext->isInComposition()) return; // 输入中不处理

	OpenCCUtil::ConvertDirection dir = m_inputContext->m_currentConvertDir; // 需在InputContext暴露接口或通过信号获取
	QString currentText = toPlainText();
    QString convertedText = OpenCCUtil::getInstance()->convert(currentText, dir);
	if (convertedText != currentText) {
		// 避免循环触发
		blockSignals(true);
		setPlainText(convertedText);
        blockSignals(false);
	}
}
//////////////////////////////////////////////////

void InputTextEdit::onCandidateSelected(const QString &text) {
	insertPlainText(text);
    hideCandidateWindow();
    // 通知InputContext提交文本
    m_inputContext->commitText(text);
}

void InputTextEdit::onAutoAddWordCheck()
{
	if (m_pendingWord.isEmpty()) return;

    // 校验是否为未收录词
    if (!m_userDict->isWordExists(m_pendingWord)) {
        // 弹出提示窗，询问是否添加
        QDialog dialog(this);
        dialog.setWindowTitle("自动造词");
        QVBoxLayout *layout = new QVBoxLayout(&dialog);
        layout->addWidget(new QLabel(QString("是否添加未收录词：%1").arg(m_pendingWord)));
        
        QCheckBox *syncCheck = new QCheckBox("同步生成繁体");
        syncCheck->setChecked(true);
        layout->addWidget(syncCheck);

        QHBoxLayout *btnLayout = new QHBoxLayout();
        QPushButton *okBtn = new QPushButton("确认");
        QPushButton *cancelBtn = new QPushButton("取消");
        btnLayout->addWidget(okBtn);
        btnLayout->addWidget(cancelBtn);
        layout->addLayout(btnLayout);

        connect(okBtn, &QPushButton::clicked, &dialog, &QDialog::accept);
        connect(cancelBtn, &QPushButton::clicked, &dialog, &QDialog::reject);

        if (dialog.exec() == QDialog::Accepted) {
            // 生成繁体（若勾选）
            QString twWord = m_pendingWord;
            if (syncCheck->isChecked()) {
                twWord = OpenCCUtil::getInstance()->convert(m_pendingWord, OpenCCUtil::ConvertDirection::S2T_TW);
            }
            // 添加到用户词库
            m_userDict->addWord(m_pendingWord, twWord);
            LogUtil::info(QString("[InputTextEdit] 自动添加词：%1（繁体：%2）").arg(m_pendingWord).arg(twWord));
        }
    }
    m_pendingWord.clear();
}
